package bjtu.tjj.simpledy.exception;

import bjtu.tjj.simpledy.common.CommonResult;
import bjtu.tjj.simpledy.common.ResultCode;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public CommonResult<Void> handleMaxUploadSizeExceededException() {
        return CommonResult.error(ResultCode.FILE_TOO_LARGE);
    }

    @ExceptionHandler(CommonException.class)
    public CommonResult<Void> handleCommonException(CommonException e) {
        return CommonResult.error(e.code);
    }

    /**
     * 对象属性参数异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<String> errors = e.getAllErrors().stream()
                .map(MessageSourceResolvable::getDefaultMessage)
                .toList();
        return CommonResult.error(ResultCode.ARGUMENT_NOT_VALID, String.join(", ", errors));
    }

    /**
     * 方法参数异常
     */
    @ExceptionHandler(HandlerMethodValidationException.class)
    public CommonResult<Void> handleHandlerMethodValidationException(HandlerMethodValidationException e) {
        List<String> errors = e.getAllErrors().stream()
                .map(MessageSourceResolvable::getDefaultMessage)
                .toList();
        return CommonResult.error(ResultCode.ARGUMENT_NOT_VALID, String.join(", ", errors));
    }

    @ExceptionHandler(NoResourceFoundException.class)
    public CommonResult<Void> handleNoResourceFoundException() {
        return CommonResult.error(ResultCode.NO_RESOURCE_FOUND);
    }

//    @ExceptionHandler(Exception.class)
//    public CommonResult<Void> handleUncaughtException(Exception e) {
//        List<String> stack = Arrays.stream(e.getStackTrace()).map(StackTraceElement::toString).toList();
//        log.error("存在未捕获的异常：\n"+e+"\n"+String.join("\n", stack));
//        return CommonResult.error(ResultCode.FAILED);
//    }
}